﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ERPStore.Extensions;

namespace ERPStore.Cart.Services
{
	public class AdminCartService
	{
		public AdminCartService(Services.CartService cartService
			, ERPStore.Services.IAccountService accountService
			, ERPStore.Services.ISalesService salesService
			, ERPStore.Services.IAddressService addressService
			)
		{
			this.CartService = cartService;
			this.AccountService = accountService;
			this.SalesService = salesService;
			this.AddressService = addressService;
		}

		protected Services.CartService CartService { get; private set; }
		protected ERPStore.Services.IAccountService AccountService { get; private set; }
		protected ERPStore.Services.ISalesService SalesService { get; private set; }
		protected ERPStore.Services.IAddressService AddressService { get; private set; }

		//public ERPStore.Models.OrderCartListResult GetOrderCartList(ERPStore.Models.OrderCartListFilter filter, int pageIndex, int pageSize)
		//{
		//    var result = new ERPStore.Models.OrderCartListResult();

		//    var list = CartRepository.GetCartList();
		//    if (filter.CartStateId.HasValue)
		//    {
		//        list = list.Where(i => i.CartStateId == filter.CartStateId.Value);
		//    }
		//    if (!filter.CouponCode.IsNullOrTrimmedEmpty())
		//    {
		//        list = list.Where(i => i.CouponCode == filter.CouponCode);
		//    }
		//    if (filter.HasLeadSource.HasValue)
		//    {
		//        list = list.Where(i => !i.LeadSourceId.IsNullOrTrimmedEmpty());
		//    }
		//    if (filter.IsPresent.HasValue)
		//    {
		//        list = list.Where(i => i.IsPresent == filter.IsPresent);
		//    }
		//    if (!filter.LeadSourceId.IsNullOrTrimmedEmpty())
		//    {
		//        list = list.Where(i => i.LeadSourceId == filter.LeadSourceId);
		//    }
		//    if (!filter.SearchTerm.IsNullOrTrimmedEmpty())
		//    {
		//        list = list.Where(i => filter.SearchTerm.IndexOf(i.Code) != -1);
		//    }
		//    if (!filter.VisitorId.IsNullOrTrimmedEmpty())
		//    {
		//        list = list.Where(i => i.VisitorId == filter.VisitorId);
		//    }

		//    var total = new ERPStore.Models.OrderCartTotal();

		//    if (filter.SortColumnName.IsNullOrTrimmedEmpty())
		//    {
		//        if (filter.SortDirection == System.ComponentModel.ListSortDirection.Descending)
		//        {
		//            list = list.OrderByDescending(filter.SortColumnName);
		//        }
		//        else
		//        {
		//            list = list.OrderBy(filter.SortColumnName);
		//        }
		//    }
		//    list = list.Skip(pageIndex * pageSize).Take(pageSize);
		//    foreach (var item in list)
		//    {
		//        result.List.Add(item.ToOrderCartModel());
		//    }

		//    result.Total = total;

		//    return result;
		//}


		public Models.OrderCartExtendedListResult GetOrderCartListByFilter(Models.OrderCartFilter filter, out int count)
		{
			count = 0;
			//var query = CartService.getcar CartRepository.GetCartList();

			//if (!filter.SearchTerm.IsNullOrTrimmedEmpty())
			//{
			//    query = query.Where(i => i.Code.IndexOf(filter.SearchTerm) != -1);
			//}

			var result = new Models.OrderCartExtendedListResult();

			//result.TotalCount = query.Count();

			//if (!filter.SortByPropertyName.IsNullOrTrimmedEmpty())
			//{
			//    if (filter.SortDirection == System.ComponentModel.ListSortDirection.Ascending)
			//    {
			//        query = query.OrderBy(filter.SortByPropertyName);
			//    }
			//    else
			//    {
			//        query = query.OrderByDescending(filter.SortByPropertyName);
			//    }
			//}
			//else
			//{
			//    query = query.OrderByDescending(i => i.Id);
			//}

			//query = query.Skip(filter.PageIndex * filter.PageSize).Take(filter.PageSize);

			//result.List = query.ToList();
			return result;
		}

		public string ConvertToOrder(string cartCode)
		{
			var cart = CartService.GetCartByCode(cartCode);

			if (cart == null
				|| cart.ItemCount == 0)
			{
				throw new Exception("CartCode does not exist");
			}

			ERPStore.Models.User user = null;
			if (cart.CustomerId.HasValue)
			{
				user = AccountService.GetUserById(cart.CustomerId.Value);
			}
			cart.AcceptCondition = true;

			ERPStore.Models.ISaleDocument order = null;

			bool isNewCustomer = false;
			string password = string.Empty;

			if (user == null)
			{
				var registration = AccountService.GetRegistrationUser(cart.VisitorId);
				if (registration == null)
				{
					throw new Exception("Registration does not exists");
				}
				user = AccountService.CreateUserFromRegistration(registration);
				cart.BillingAddress = user.DefaultAddress;
				cart.DeliveryAddress = user.LastDeliveredAddress;
				password = registration.Password;
				if (registration.IsSameBillingAddress)
				{
					registration.BillingAddressCity = registration.ShippingAddressCity;
					registration.BillingAddressCountryId = registration.ShippingAddressCountryId;
					registration.BillingAddressRecipientName = registration.ShippingAddressRecipientName;
					registration.BillingAddressRegion = registration.ShippingAddressRegion;
					registration.BillingAddressStreet = registration.ShippingAddressStreet;
					registration.BillingAddressZipCode = registration.ShippingAddressZipCode;
				}

				user = AccountService.RegisterUser(registration);
				isNewCustomer = true;

				// Affectation de l'adresse de livraison
				cart.DeliveryAddress = new ERPStore.Models.Address();
				cart.DeliveryAddress.City = registration.ShippingAddressCity;
				cart.DeliveryAddress.CountryId = registration.ShippingAddressCountryId;
				cart.DeliveryAddress.RecipientName = registration.ShippingAddressRecipientName;
				cart.DeliveryAddress.Region = registration.ShippingAddressRegion;
				cart.DeliveryAddress.Street = registration.ShippingAddressStreet;
				cart.DeliveryAddress.ZipCode = registration.ShippingAddressZipCode;

				cart.CustomerId = user.Id;
			}

			// Affectation de l'adresse de facturation
			cart.BillingAddress = cart.BillingAddress ?? user.DefaultAddress;

			// Traitement de l'export
			var principal = new ERPStore.Models.UserPrincipal(cart.VisitorId);
			principal.CurrentUser = user;
			SalesService.ProcessExport(cart, principal);

			// création de la commande
			order = SalesService.CreateOrderFromCart(user, cart, cart.PaymentModeName);
			using (var ts = TransactionHelper.GetNewReadCommitted())
			{
				cart.ConvertedEntityId = order.Id;
				CartService.Save(cart);
				ts.Complete();
			}

			if (isNewCustomer)
			{
				AccountService.CloseRegistrationUser(cart.VisitorId, user.Id);
			}

			return order.Code;
		}
	}
}
